#!/usr/bin/env python3
# -*- coding:utf-8 -*-
# @Time: 2019/7/21  21:50
# @Author: 余浪人
# @email: yulangren520@gmail.com
from flask import request
from datetime import datetime
import time
from apps.lib.public import batch_add


def aliPay():
    from apps.models.system_model import TL_PayConf_Model
    from alipay import AliPay
    try:
        pay = TL_PayConf_Model.query.filter_by().first()
        alipay = AliPay(
            appid=pay.app_id.strip(),
            app_notify_url=None,  # 默认回调url
            sign_type="RSA2",
            alipay_public_key_string='-----BEGIN PUBLIC KEY-----\n' + pay.public_key + '\n-----END PUBLIC KEY-----',
            app_private_key_string='-----BEGIN RSA PRIVATE KEY-----\n' + pay.private_key + '\n-----END RSA PRIVATE KEY-----',
            debug=True  # 默认False
        )
        return alipay
    except:
        return {'status': 4, 'msg': '支付系统配置错误'}


def verify_pay_statu():
    '''
    验证是否支付成功
    :return:
    '''
    alipay = aliPay()
    paid = False
    global result
    try:
        for i in range(10):
            result = alipay.api_alipay_trade_query(out_trade_no=request.args.get('out_trade_no'))
            if result.get("trade_status", "") == "TRADE_SUCCESS" and result.get('code') == '10000':
                paid = True
                break
            time.sleep(10)
        if paid is False:  # 判断是否支付成功
            context = {'status': 1, 'msg': "支付失败!"}
        else:
            context = {'status': 0, 'msg': "支付成功!", "data": result}
        if paid is False:
            alipay.api_alipay_trade_cancel(out_trade_no=request.args.get('out_trade_no'))
    except:
        context = {'status': 4, 'msg': "支付系统配置错误!"}
    return context


def save_order(data: dict):
    '''
    保存订单信息
    :param data:
    :return: 成功/失败
    '''
    from apps.models.order_model import TL_PayOrder_Model, db
    buyer_logon_ID = data.get('buyer_logon_id')  # 买家登陆ID
    buyer_user_ID = data.get('buyer_user_id')  # 买家用户ID
    send_pay_date = datetime.strptime(data.get('send_pay_date'), "%Y-%m-%d %H:%M:%S")  # 购买时间
    total_amount = data.get('total_amount')  # 金额
    out_trade_no = data.get('out_trade_no')  # 系统订单编号
    trade_no = data.get('trade_no')  # 支付宝订单编号
    message = data.get('msg')  # 订单状态

    dbData = {"buyer_logon_ID": buyer_logon_ID, "buyer_user_ID": buyer_user_ID, "send_pay_date": send_pay_date,
              "total_amount": total_amount, "out_trade_no": out_trade_no, "trade_no": trade_no, "message": message}
    return batch_add(TL_PayOrder_Model, db, [dbData])


def save_goods(data: list):
    '''
    保存订单(预)
    :param data:
    :return:
    '''
    from apps.models.order_model import TL_Order_Model, db
    return batch_add(TL_Order_Model, db, data)
